using MediatR;
using WMS.Domain;
using WMS.ErrorCode;
using WMS.Infrasturcture.Interfaces;
using WMS.WebApiWrite.Application.Command;

namespace WMS.WebApiWrite.Application.Commandhandler
{
    /// <summary>
    /// 新增仓库信息命令处理器
    /// </summary>
    public class AddWarehouseCommandHandler : IRequestHandler<AddWarehouseCommand, ApiResult<bool>>
    {
        private readonly IBaseRepository<WarehouseInfo> warehouseRepository;
        private static readonly Random random = new Random();

        /// <summary>
        /// 构造函数，注入仓库仓储
        /// </summary>
        public AddWarehouseCommandHandler(IBaseRepository<WarehouseInfo> warehouseRepository)
        {
            this.warehouseRepository = warehouseRepository;
        }

        /// <summary>
        /// 处理新增仓库信息命令
        /// </summary>
        public async Task<ApiResult<bool>> Handle(AddWarehouseCommand request, CancellationToken cancellationToken)
        {
            try
            {
                // 自动生成唯一的仓库编码（格式：时间戳+4位随机数）
                var warehouseCode = GenerateUniqueWarehouseCode();

                // 创建仓库信息实体
                var warehouseInfo = new WarehouseInfo
                {
                    WarehouseCode = warehouseCode, // 使用自动生成的编码
                    WarehouseName = request.WarehouseDTO.WarehouseName,
                    Warehousecapacity = request.WarehouseDTO.Warehousecapacity,
                    SupervisorId = request.WarehouseDTO.SupervisorId,
                    WarehouseDeptId = request.WarehouseDTO.WarehouseDeptId,
                    WarehousePhone = request.WarehouseDTO.WarehousePhone,
                    WarehouseAddress = request.WarehouseDTO.WarehouseAddress,
                    WarehouseState = request.WarehouseDTO.WarehouseState,
                    WarehouseLockdown = request.WarehouseDTO.WarehouseLockdown,
                    WarehouseContent = request.WarehouseDTO.WarehouseContent,
                    IsDeleted = false, // 新建数据默认未删除
                    DataStatus = request.WarehouseDTO.DataStatus, // 数据状态：1保存草稿 2保存为新增 3保存
                    CreateName = request.WarehouseDTO.OperatorName,
                    CreateTime = DateTime.Now
                };

                // 执行新增操作
                var result = await warehouseRepository.AddAsync(warehouseInfo);

                if (result > 0)
                {
                    // 根据不同的数据状态返回不同的成功消息
                    string message = request.WarehouseDTO.DataStatus switch
                    {
                        1 => "保存草稿成功",
                        2 => "新增仓库信息成功",
                        3 => "保存仓库信息成功",
                        _ => "操作成功"
                    };

                    return new ApiResult<bool>
                    {
                        Code = ApiResultEnum.新增成功,
                        Message = message,
                        Data = true
                    };
                }
                else
                {
                    return new ApiResult<bool>
                    {
                        Code = ApiResultEnum.新增失败,
                        Message = "新增仓库信息失败",
                        Data = false
                    };
                }
            }
            catch (Exception ex)
            {
                return new ApiResult<bool>
                {
                    Code = ApiResultEnum.新增失败,
                    Message = $"新增仓库信息异常：{ex.Message}",
                    Data = false
                };
            }
        }

        /// <summary>
        /// 生成唯一的仓库编码（格式：年月日+4位随机数，如：202510291234）
        /// </summary>
        private long GenerateUniqueWarehouseCode()
        {
            long code;
            int maxAttempts = 100; // 最大尝试次数
            int attempts = 0;

            do
            {
                // 生成格式：年月日（8位）+ 4位随机数
                string datePart = DateTime.Now.ToString("yyyyMMdd"); // 例如：20251029
                int randomNumber = random.Next(1000, 10000); // 4位随机数：1000-9999
                code = long.Parse($"{datePart}{randomNumber}"); // 例如：202510291234

                attempts++;
                if (attempts >= maxAttempts)
                {
                    // 如果尝试多次仍重复，使用时分秒替代随机数
                    string timePart = DateTime.Now.ToString("HHmmss");
                    code = long.Parse($"{datePart}{timePart}");
                    break;
                }
            } while (warehouseRepository.GetAll().Where(x => !x.IsDeleted).Any(x => x.WarehouseCode == code)); // 只检查未删除的记录

            return code;
        }
    }
}

